package com.guda.mp.service.impl;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.app.core.base.BaseDao;
import com.app.core.base.BaseServiceImpl;
import com.app.core.base.PageQuery;
import com.app.core.common.AppBizCache;
import com.app.core.common.NoData;
import com.app.core.common.Result;
import com.app.core.util.SysConfig;
import com.app.core.web.context.RequestContext;
import com.github.pagehelper.Page;
import com.google.common.collect.Lists;
import com.guda.mp.dao.HouseDao;
import com.guda.mp.dao.MonitorTargetDao;
import com.guda.mp.dao.ProjectDao;
import com.guda.mp.dao.TaskCenterDao;
import com.guda.mp.dao.TaskCenterProblemDao;
import com.guda.mp.service.HouseService;
import com.guda.mp.service.TaskCenterService;
import com.guda.mp.vo.HouseVo;
import com.guda.mp.vo.MonitorTargetVo;
import com.guda.mp.vo.ProjectVo;
import com.guda.mp.vo.TaskCenterProblemVo;
import com.guda.mp.vo.TaskCenterVo;

@Service
@Transactional
public class HouseServiceImpl extends BaseServiceImpl<HouseVo> implements HouseService {

    @Autowired
    private TaskCenterDao taskCenterDao;
    @Autowired
    private TaskCenterProblemDao taskCenterProblemDao;
    @Autowired
    private MonitorTargetDao monitorTargetDao;
    @Autowired
    private HouseDao houseDao;
    @Autowired
    private TaskCenterService taskCenterService;
    @Autowired
    private ProjectDao projectDao;

    @Override
    protected BaseDao<HouseVo> getDao() {
        return this.houseDao;
    }
    @Override
    public Page<HouseVo> houseListVersion2(PageQuery pageQuery, HouseVo query) {
        Long userId = RequestContext.getUserSession().getLoginUser().getId();
        query.setUserId(userId);

        /* 查询负责的房屋 */
        super.setPageQuery(pageQuery);

        Page<HouseVo> housePage = null;
        Map<Long, Map<Long, String>> streetMap = null;
        if (RequestContext.getLoginUserName().equals("admin")) {
            housePage = (Page<HouseVo>) monitorTargetDao.selectInspectionHouseAll(query);
        } else {
            housePage = (Page<HouseVo>) monitorTargetDao.selectInspectionUserOwnerHouse(query);
        }

        return housePage;
    }
    @Override
    public Page<MonitorTargetVo> houseList(PageQuery pageQuery, HouseVo query) {
        Long userId = RequestContext.getUserSession().getLoginUser().getId();
        query.setUserId(userId);

        /* 查询负责的房屋 */
        super.setPageQuery(pageQuery);

        Page<HouseVo> housePage = null;
        Map<Long, Map<Long, String>> streetMap = null;
        if (RequestContext.getLoginUserName().equals("admin")) {
            housePage = (Page<HouseVo>) monitorTargetDao.selectInspectionHouseAll(query);
            streetMap = monitorTargetDao.selectInspectionHouseStreetNameAll();
        } else {
            housePage = (Page<HouseVo>) monitorTargetDao.selectInspectionUserOwnerHouse(query);
            streetMap = monitorTargetDao.selectInspectionUserOwnerHouseStreetName(userId);
        }

        // 查询房屋的问题统计
        setTaskProblemLevelCount(housePage);

        /* 查询房屋所属的街道 */
        Map<String, List<HouseVo>> houseMap = new LinkedHashMap<>();
        for (HouseVo houseVo : housePage) {
            Map<Long, String> targetVo = streetMap.get(houseVo.getMonitorTargetId());
            if (targetVo == null) {
                continue;
            }
            System.out.println(houseVo.getName());

            String streetName = targetVo.get("name");
            List<HouseVo> list = houseMap.get(targetVo.get("name"));
            if (list == null) {
                list = new ArrayList<>();
                houseMap.put(streetName, list);
            }

            HouseVo house = new HouseVo();
            house.setMonitorTargetId(houseVo.getMonitorTargetId());
            house.setName(houseVo.getName());
            house.setAddress(houseVo.getAddress());
            house.setProblemCountMap(houseVo.getProblemCountMap());
            house.setDataUuid(houseVo.getDataUuid());
            house.setBindCardFlag(houseVo.getBindCardFlag());
            list.add(house);
        }

        // map转为list返回
        List<MonitorTargetVo> resultList = new ArrayList<>();
        Set<String> keySet = houseMap.keySet();
        for (String key : keySet) {
            MonitorTargetVo targetVo = new MonitorTargetVo();
            targetVo.setName(key);
            targetVo.setHouseList(houseMap.get(key));
            resultList.add(targetVo);
        }

        Page<MonitorTargetVo> page = new Page<>(housePage.getPageNum(), housePage.getPageSize());
        page.setTotal(housePage.getTotal());
        page.addAll(resultList);

        return page;
    }

    @Override
    public HouseVo houseDetail(long monitorTargetId) {
        HouseVo houseVo = houseDao.selectByMonitorTargetId(monitorTargetId);
        setTaskProblemLevelCount(houseVo);

        /* 房屋所属项目 */
        if (houseVo.getProjectId() != null) {
            ProjectVo projectVo = projectDao.selectById(houseVo.getProjectId());
            if (projectVo != null) {
                houseVo.setProjectName(projectVo == null ? null : projectVo.getName());
            }
        }

        /* 翻译字典项 */
        houseVo.setStructTypeName(AppBizCache.dictDecode("structType", houseVo.getStructType()));
        houseVo.setLandNatureName(AppBizCache.dictDecode("landNature", houseVo.getLandNature()));
        houseVo.setOwnNatureName(AppBizCache.dictDecode("ownNature", houseVo.getOwnNature()));
        houseVo.setBaseTypeInfoName(AppBizCache.dictDecode("baseTypeInfo", houseVo.getBaseTypeInfo()));
        houseVo.setHousePlaceTypeName(AppBizCache.dictDecode("housePlaceType", houseVo.getHousePlaceType()));
        houseVo
            .setChemicalAttackTypeName(AppBizCache.dictDecode("chemicalAttackType", houseVo.getChemicalAttackType()));
        houseVo.setChangeTypeName(AppBizCache.dictDecode("changeType", houseVo.getChangeType()));
        houseVo.setAddLayerTypeName(AppBizCache.dictDecode("addLayerType", houseVo.getAddLayerType()));
        houseVo.setRepairTypeName(AppBizCache.dictDecode("repairType", houseVo.getRepairType()));
        houseVo.setHistoricalDisasterTypeName(
            AppBizCache.dictDecode("historicalDisasterType", houseVo.getHistoricalDisasterType()));
        houseVo.setUseFuncChangeTypeName(AppBizCache.dictDecode("useFuncChangeType", houseVo.getUseFuncChangeType()));
        houseVo.setAppraisalTypeName(AppBizCache.dictDecode("appraisalType", houseVo.getAppraisalType()));
        houseVo.setDrawingDataTypeName(AppBizCache.dictDecode("drawingDataType", houseVo.getDrawingDataType()));

        return houseVo;
    }

    @Override
    public List<TaskCenterProblemVo> houseProblemList(long monitorTargetId) {
        List<TaskCenterProblemVo> list = taskCenterProblemDao.selectByMonitorTargetId(monitorTargetId);

        return list;
    }

    @Override
    public List<TaskCenterVo> inspectionRecordList(long monitorTargetId) {
        TaskCenterVo query = new TaskCenterVo();
        query.setMonitorTargetId(monitorTargetId);
        List<TaskCenterVo> list = taskCenterDao.selectInspectionRecordPage(query);
        taskCenterService.setTaskProblemLevelCount(list);

        return list;
    }

    @Override
    public Result<NoData> updateLocaion(long monitorTargetId, Double lat, Double lng) {
        MonitorTargetVo targetVo = monitorTargetDao.selectById(monitorTargetId);
        HouseVo bean = new HouseVo();
        bean.setId(targetVo.getRefId());
        bean.setLat(lat);
        bean.setLng(lng);
        houseDao.updateById(bean);

        return Result.success();
    }

    /** 设置多个task的问题统计数量 */
    private void setTaskProblemLevelCount(List<HouseVo> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        List<Long> idList = new ArrayList<>();
        for (HouseVo houseVo : list) {
            idList.add(houseVo.getMonitorTargetId());
        }

        List<TaskCenterProblemVo> probList = taskCenterProblemDao.selectCountByMonitorTargetIdList(idList);
        for (HouseVo tc : list) {
            for (TaskCenterProblemVo prob : probList) {
                if (tc.getMonitorTargetId() == prob.getMonitorTargetId()) {
                    Map<String, Long> problemCountMap = tc.getProblemCountMap();
                    if (problemCountMap == null) {
                        problemCountMap = new LinkedHashMap<>();
                        tc.setProblemCountMap(problemCountMap);
                    }
                    problemCountMap.put(prob.getCheckProblemLevel().toString(), prob.getCountNum());
                }
            }
        }
    }

    /** 设置单个task的问题统计数量 */
    private void setTaskProblemLevelCount(HouseVo vo) {
        setTaskProblemLevelCount(Lists.newArrayList(vo));
    }

    @Override
    public Result<NoData> bindCardSuccess(Long targetId) {
        MonitorTargetVo bean = new MonitorTargetVo();
        bean.setId(targetId);
        bean.setBindCardFlag(1);
        monitorTargetDao.updateById(bean);

        return Result.success();
    }

    @Override
    public List<HouseVo> selectBizList(HouseVo bean) {
        return houseDao.selectBizList(bean);
    }

    @Override
    public Result<NoData> updateHouseImg(Long monitorTargetId, String houseImg) {
        MonitorTargetVo monitorTargetVo = monitorTargetDao.selectById(monitorTargetId);
        Long houseId = monitorTargetVo.getRefId();
        HouseVo updateHouse = new HouseVo();
        updateHouse.setId(houseId);
        updateHouse.setHouseImg(SysConfig.get("qiniu.domain") + houseImg);
        houseDao.updateById(updateHouse);

        return Result.success();
    }

}
